const app = getApp();
const qiniuUploader = require("../../../utils/qiniuUploader-min.js");
import grace from "../../../utils/grace.js";

grace.page({
  /**
   * 页面的初始数据
   */
  data: {
    category: [],
    categoryStr: [],
    index: 0,
    imageUrls: [], // 上传七牛云后的路径
    tmpImagePaths: [] // 用户选择的图片路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    wx.getStorageSync('school_id')
    let url = app.globalData.api + '/api/v1.0/posterCategory/' + school_id;
    that.$http.get(url).then((res) => {
      if (res.data.code == 0) {
        that.$data.category = res.data.data;
        for (let i = 0; i < res.data.data.length; i++) {
          that.$data.categoryStr.push(res.data.data[i].name);
        }
      }
    }).catch(err => {
      console.log(err.status, err.message);
    })

    that.initQiniu();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  // 初始化七牛相关参数
  initQiniu() {
    let options = {
      uploadURL: 'https://up-z2.qbox.me',
      uptokenURL: app.globalData.api + '/api/v1.0/qiniuUptoken',
      domain: 'https://img.houdeyun.com/' // domain 为七牛空间（bucket)对应的域名
    };
    qiniuUploader.init(options);
  },

  didPressChooesImage() {
    let that = this;
    // 微信 API 选文件
    wx.chooseImage({
      count: 9 - that.$data.imageUrls.length,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(photo) {
        if (that.$data.tmpImagePaths.length < 9) {
          for (let i = 0; i < photo.tempFilePaths.length; i++) {
            that.$data.tmpImagePaths.push(photo.tempFilePaths[i]);
          }
        } else {
          wx.showModal({
            title: '错误',
            content: '最多支持9张图片',
            showCancel: false
          })
        }
      }
    })
  },

  previewImage: function(e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.imageUrls
    })
  },

  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  formSubmit: function(e) {
    let that = this;

    if (!e.detail.value.body) {
      wx.showModal({
        title: '提示',
        content: '请输入话题内容！',
        showCancel: false
      })
      return;
    }

    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载中...',
    });

    // 交给七牛上传
    let count = 0; // count记录当前已经上传到第几张图片
    new Promise(function(resolve, reject) {
      for (let i = 0; i < that.$data.tmpImagePaths.length; i++) {
        qiniuUploader.upload(that.$data.tmpImagePaths[i], (res) => {
          count++;
          that.$data.imageUrls.push(res.imageURL);
          if (count == that.$data.tmpImagePaths.length) {
            resolve(that.$data.imageUrls);
          }
        }, (error) => {
          reject('error');
          console.error('error: ' + JSON.stringify(error));
        });
      }
    }).then(function(imgList) {
      // 发布帖子
      wx.getStorageSync('school_id')
      let url = app.globalData.api + '/api/v1.0/poster/' + school_id;
      let params = {
        token: token,
        partner_id: wx.getStorageSync('partner_id'),
        parent_id: false,
        categ_id: that.$data.category[that.$data.index].id,
        body: e.detail.value.body,
        images: imgList
      }
      that.$http.post(url, params).then((res) => {
        if (res.data.code == 0) {
          // 发布成功
          console.log('发布成功');
          wx.navigateTo({
            url: '/pages/circle/index/list?category_id=' + that.$data.category[that.$data.index].id
          })
        } else {
          wx.showModal({
            title: '错误',
            content: res.data.msg,
            showCancel: false
          })
        }
        wx.hideLoading();
      }).catch(err => {
        console.log(err.status, err.message);
      })
    })
  }
})